package com.gloaba.gateway.handler;


import com.gloaba.common.core.domain.R;
import com.gloaba.common.core.exception.AccessIpLimitException;
import com.gloaba.common.core.exception.UnAuthorizedException;
import com.gloaba.gateway.service.IApiLogService;
import com.gloaba.gateway.utils.WebFluxUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关统一异常处理
 *
 * @author ruoyi
 */
@Order(-1)
@Configuration
@RequiredArgsConstructor
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private final IApiLogService iApiLogService;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }

        String msg;
        int resultCode = R.FAIL;

        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex.getMessage(),ex);

        HttpStatus status = HttpStatus.OK;
        if (ex instanceof NotFoundException) {
            msg = "服务未找到";
        } else if (ex instanceof AccessIpLimitException) {
            //ip访问受限
            msg = "Access Ip Limited";
            resultCode = com.gloaba.common.core.constant.HttpStatus.NOT_ACCEPTABLE;
            status = HttpStatus.NOT_ACCEPTABLE;
        } else if (ex instanceof ResponseStatusException) {
            ResponseStatusException responseStatusException = (ResponseStatusException) ex;
            msg = responseStatusException.getMessage();
        } else if (ex instanceof UnAuthorizedException) {
            UnAuthorizedException exception = (UnAuthorizedException) ex;
            msg = exception.getMessage();
            resultCode = com.gloaba.common.core.constant.HttpStatus.UNAUTHORIZED;
        } else {
            msg = "内部服务器错误";
        }

        iApiLogService.updateApiLog(exchange, ex);
        return WebFluxUtils.webFluxResponseWriter(response,status, msg, resultCode);
    }
}
